package com.tencent.qcloud.tim.uikit.modules.contact

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.manor.common.http.HttpCallback
import com.manor.common.ktx.toBeanList
import com.tencent.imsdk.v2.V2TIMFriendInfo
import com.tencent.imsdk.v2.V2TIMGroupInfo
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMValueCallback
import com.tencent.qcloud.tim.uikit.R
import com.tencent.qcloud.tim.uikit.bean.GroupFriendBean
import com.tencent.qcloud.tim.uikit.component.CustomLinearLayoutManager
import com.tencent.qcloud.tim.uikit.component.indexlib.IndexBar.widget.IndexBar
import com.tencent.qcloud.tim.uikit.component.indexlib.suspension.SuspensionDecoration
import com.tencent.qcloud.tim.uikit.http.TkHttpConst
import com.tencent.qcloud.tim.uikit.http.TkHttpUtil
import com.tencent.qcloud.tim.uikit.http.TkHttpUtil.getGroupFMember
import com.tencent.qcloud.tim.uikit.modules.group.info.GroupInfo
import com.tencent.qcloud.tim.uikit.utils.BackgroundTasks
import com.tencent.qcloud.tim.uikit.utils.TUIKitLog
import com.tencent.qcloud.tim.uikit.utils.ThreadHelper
import com.tencent.qcloud.tim.uikit.utils.ToastUtil
import java.util.*

class ContactListView : LinearLayout {
    private var mRv: RecyclerView? = null
    var adapter: ContactAdapter? = null
        private set
    private var mManager: CustomLinearLayoutManager? = null
    private var mData: MutableList<ContactItemBean> = ArrayList()
    private var mDecoration: SuspensionDecoration? = null
    private var mContactLoadingBar: ProgressBar? = null
    private var mGroupInfo: GroupInfo? = null

    /**
     * 右侧边栏导航区域
     */
    private var mIndexBar: IndexBar? = null

    /**
     * 显示指示器DialogText
     */
    private var mTvSideBarHint: TextView? = null

    constructor(context: Context?) : super(context) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {
        View.inflate(context, R.layout.contact_list, this)
        mRv = findViewById(R.id.contact_member_list)
        mManager = CustomLinearLayoutManager(context)
        mRv?.layoutManager = mManager
        adapter = ContactAdapter(mData)
        mRv?.adapter = adapter
        mRv?.addItemDecoration(SuspensionDecoration(context, mData).also { mDecoration = it })
        mTvSideBarHint = findViewById(R.id.contact_tvSideBarHint)
        mIndexBar = findViewById(R.id.contact_indexBar)
        mIndexBar?.setPressedShowTextView(mTvSideBarHint)
                ?.setNeedRealIndex(false)
                ?.setLayoutManager(mManager)
        mContactLoadingBar = findViewById(R.id.contact_loading_bar)
    }

    fun setDataSource(data: MutableList<ContactItemBean>) {
        mContactLoadingBar?.visibility = View.GONE
        mData = data
        adapter?.setDataSource(mData)
        mIndexBar?.setSourceDatas(mData)?.invalidate()
        mDecoration?.setDatas(mData)
    }

    fun setSingleSelectMode(mode: Boolean) {
        adapter?.setSingleSelectMode(mode)
    }

    fun setOnSelectChangeListener(selectChangeListener: OnSelectChangedListener?) {
        adapter?.setOnSelectChangedListener(selectChangeListener)
    }

    fun setOnItemClickListener(listener: OnItemClickListener?) {
        adapter?.setOnItemClickListener(listener)
    }

    fun loadDataSource(dataSource: Int) {
        mContactLoadingBar?.visibility = View.VISIBLE
        mData.clear()
        when (dataSource) {
            DataSource.FRIEND_LIST -> loadFriendListDataAsync()
            DataSource.BLACK_LIST -> loadBlackListData()
            DataSource.GROUP_LIST -> loadGroupListData()
            DataSource.CONTACT_LIST -> {
                mData.add(ContactItemBean(resources.getString(R.string.new_friend))
                        .setTop(true).setBaseIndexTag(ContactItemBean.INDEX_STRING_TOP) as ContactItemBean)
                mData.add(ContactItemBean(resources.getString(R.string.group)).setTop(true).setBaseIndexTag(ContactItemBean.INDEX_STRING_TOP) as ContactItemBean)
                mData.add(ContactItemBean(resources.getString(R.string.blacklist)).setTop(true).setBaseIndexTag(ContactItemBean.INDEX_STRING_TOP) as ContactItemBean)
                loadFriendListDataAsync()
            }
            else -> {
            }
        }
        adapter?.notifyDataSetChanged()
    }

    fun setGroupInfo(groupInfo: GroupInfo?) {
        mGroupInfo = groupInfo
    }

    private fun updateStatus(beanList: List<ContactItemBean>) {
        if (mGroupInfo == null) {
            return
        }
        val list = mGroupInfo?.memberDetails
        var needFresh = false
        list?.run {
            for (info in this) {
                for (bean in beanList) {
                    if (info.account == bean.id) {
                        bean.isSelected = true
                        bean.isEnable = false
                        needFresh = true
                    }
                }
            }
        }

        if (needFresh) {
            BackgroundTasks.getInstance().runOnUiThread { adapter?.notifyDataSetChanged() }
        }
    }

    private fun loadFriendListDataAsync() {
        TUIKitLog.i(TAG, "loadFriendListDataAsync")
//        ThreadHelper.INST.execute { // 压测时数据量比较大，query耗时比较久，所以这里使用新线程来处理
//            V2TIMManager.getFriendshipManager().getFriendList(object : V2TIMValueCallback<List<V2TIMFriendInfo?>?> {
//                override fun onError(code: Int, desc: String) {
//                    TUIKitLog.e(TAG, "loadFriendListDataAsync err code:$code, desc:$desc")
//                    ToastUtil.toastShortMessage("loadFriendList error code = $code, desc = $desc")
//                }
//
//                override fun onSuccess(v2TIMFriendInfos: List<V2TIMFriendInfo?>?) {
//                    var v2TIMFriendInfos = v2TIMFriendInfos
//                    if (v2TIMFriendInfos == null) {
//                        v2TIMFriendInfos = ArrayList()
//                    }
//                    TUIKitLog.i(TAG, "loadFriendListDataAsync->getFriendList:" + v2TIMFriendInfos.size)
//                    assembleFriendListData(v2TIMFriendInfos)
//                }
//            })
//        }

        ThreadHelper.INST.execute {
            mGroupInfo?.id?.run { getGroupFMember(this, object : HttpCallback(){
                override fun onSuccess(code: Int, msg: String?, info: String?) {
                    if (code == 0 && info!=null && info.isNotEmpty()){
                        val list = info.toBeanList<GroupFriendBean>()
                        for (item in list) {
                            val bean = ContactItemBean()
                            bean.remark = item.userNickname
                            bean.nickname = item.userNickname
                            bean.avatarurl = item.avatarThumb
                            bean.id = item.uid
                            if (bean.nickname.isNotEmpty() || bean.remark.isNotEmpty())
                                mData.add(bean)
                        }
                        updateStatus(mData)
                        setDataSource(mData)
                    }
                }

            })
            }
        }


    }

    //    private void fillFriendListData(final List<V2TIMFriendInfo> timFriendInfoList) {
    //        // 外部调用是在其他线程里面，但是更新数据同时会刷新UI，所以需要放在主线程做。
    //        BackgroundTasks.getInstance().runOnUiThread(new Runnable() {
    //            @Override
    //            public void run() {
    //                if (timFriendInfoList.size() == 0) {
    //                    TIMFriendshipManager.getInstance().getFriendList(new TIMValueCallBack<List<TIMFriend>>() {
    //                        @Override
    //                        public void onError(int code, String desc) {
    //                            TUIKitLog.e(TAG, "getFriendList err code = " + code);
    //                            mContactLoadingBar.setVisibility(GONE);
    //                        }
    //
    //                        @Override
    //                        public void onSuccess(List<TIMFriend> timFriends) {
    //                            if (timFriends == null) {
    //                                timFriends = new ArrayList<>();
    //                            }
    //                            TUIKitLog.i(TAG, "getFriendList success result = " + timFriends.size());
    //                            assembleFriendListData(timFriends);
    //                        }
    //                    });
    //                } else {
    //                    assembleFriendListData(timFriendInfoList);
    //                }
    //            }
    //        });
    //    }
    private fun assembleFriendListData(timFriendInfoList: List<V2TIMFriendInfo?>) {
        for (timFriendInfo in timFriendInfoList) {
            val info = ContactItemBean()
            info.covertTIMFriend(timFriendInfo)
            mData.add(info)
        }
        updateStatus(mData)
        setDataSource(mData)
    }

    private fun loadBlackListData() {
        TUIKitLog.i(TAG, "loadBlackListData")
        V2TIMManager.getFriendshipManager().getBlackList(object : V2TIMValueCallback<List<V2TIMFriendInfo?>> {
            override fun onError(code: Int, desc: String) {
                TUIKitLog.e(TAG, "getBlackList err code = $code, desc = $desc")
                ToastUtil.toastShortMessage("Error code = $code, desc = $desc")
                mContactLoadingBar?.visibility = View.GONE
            }

            override fun onSuccess(v2TIMFriendInfos: List<V2TIMFriendInfo?>) {
                TUIKitLog.i(TAG, "getBlackList success: " + v2TIMFriendInfos.size)
                if (v2TIMFriendInfos.isEmpty()) {
                    TUIKitLog.i(TAG, "getBlackList success but no data")
                }
                mData.clear()
                for (timFriendInfo in v2TIMFriendInfos) {
                    val info = ContactItemBean()
                    info.covertTIMFriend(timFriendInfo).isBlackList = true
                    mData.add(info)
                }
                setDataSource(mData)
            }
        })

//        TIMFriendshipManager.getInstance().getBlackList(new TIMValueCallBack<List<TIMFriend>>() {
//            @Override
//            public void onError(int i, String s) {
//                TUIKitLog.e(TAG, "getBlackList err code = " + i + ", desc = " + s);
//                ToastUtil.toastShortMessage("Error code = " + i + ", desc = " + s);
//                mContactLoadingBar.setVisibility(GONE);
//            }
//
//            @Override
//            public void onSuccess(List<TIMFriend> timFriends) {
//                TUIKitLog.i(TAG, "getBlackList success: " + timFriends.size());
//                if (timFriends.size() == 0) {
//                    TUIKitLog.i(TAG, "getBlackList success but no data");
//                }
//                mData.clear();
//                for (TIMFriend timFriend : timFriends) {
//                    ContactItemBean info = new ContactItemBean();
//                    info.covertTIMFriend(timFriend).setBlackList(true);
//                    mData.add(info);
//                }
//                setDataSource(mData);
//            }
//        });
    }

    private fun loadGroupListData() {
        TUIKitLog.i(TAG, "loadGroupListData")
        V2TIMManager.getGroupManager().getJoinedGroupList(object : V2TIMValueCallback<List<V2TIMGroupInfo?>> {
            override fun onError(code: Int, desc: String) {
                TUIKitLog.e(TAG, "getGroupList err code = $code, desc = $desc")
                ToastUtil.toastShortMessage("Error code = $code, desc = $desc")
                mContactLoadingBar?.visibility = View.GONE
            }

            override fun onSuccess(v2TIMGroupInfos: List<V2TIMGroupInfo?>) {
                TUIKitLog.i(TAG, "getGroupList success: " + v2TIMGroupInfos.size)
                if (v2TIMGroupInfos.isEmpty()) {
                    TUIKitLog.i(TAG, "getGroupList success but no data")
                }
                mData.clear()
                for (info in v2TIMGroupInfos) {
                    val bean = ContactItemBean()
                    mData.add(bean.covertTIMGroupBaseInfo(info))
                }
                setDataSource(mData)
            }
        })
    }

    val groupData: List<ContactItemBean>
        get() = mData


    override fun onDetachedFromWindow() {
        TkHttpUtil.cancel(TkHttpConst.GET_GROUP_F_MEMBER)
        super.onDetachedFromWindow()
    }


    public interface OnSelectChangedListener {
        fun onSelectChanged(contact: ContactItemBean?, selected: Boolean)
    }

    public interface OnItemClickListener {
        fun onItemClick(position: Int, contact: ContactItemBean?)
    }

    companion object {

        val TAG = ContactListView::class.java.simpleName
        private const val INDEX_STRING_TOP = "↑"
    }
}